package com.iwunu.gateway.service.impl;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iwunu.gateway.service.ProtocolDataService;
import com.iwunu.gateway.util.ByteTools;
import com.iwunu.gateway.util.CreateOfflinePasswordUtil;
import com.iwunu.gateway.util.JsXxetaUtil;
import com.iwunu.iot.common.util.DataUtil;
import com.iwunu.iot.common.util.StringUtil;

/**
 * @author harvey
 * @date 2019/7/22 3:07 PM
 * @description
 */
@Service
public class ProtocolDataServiceImpl implements ProtocolDataService{
	
    @Autowired
    private JsXxetaUtil jsXxetaUtil;
    
       /**
     * 2.6 绑定
     * @param baseCode
     * @return
     */
    public  Map<String,String> bindLock(String baseCode,String authorization,String type){
    	 String openId = StringUtils.leftPad(baseCode, 8, "7");
        String lockMode = "2";
        return returnMap(jsXxetaUtil.bindLock(baseCode,openId,lockMode).toUpperCase());
    }
    /**
  * 2.6.1 绑定
  * @param baseCode
  * @return
  */
 public  Map<String,String> bindLock(String baseCode){
	 int i=(int)(Math.random()*900)+100;
	 baseCode = StringUtils.leftPad(baseCode, 8, "0");
     String openId =(baseCode+ i).substring(0, 8);;
     String lockMode = "2";
     return returnMap(jsXxetaUtil.bindLock(baseCode,openId,lockMode).toUpperCase());
 }
    /**
     * 2.5 解绑
     * @param baseCode
     * @return
     */
    public  Map<String,String> unBindLock(String authorization,String baseCode){
    	 String openId = StringUtils.leftPad(baseCode, 8, "7");
    	 return returnMap(jsXxetaUtil.unbindLock(baseCode,openId).toUpperCase());
        
    }
    /**
     * 2.5.1 解绑
     * @param baseCode
     * @return
     */
    public  Map<String,String> unBindLock(String baseCode){
    	 String openId = baseCode;
    	 return returnMap(jsXxetaUtil.unbindLock(baseCode,openId).toUpperCase());
        
    }

    /**
     * u1单个指令开锁
     * @param adminPwd
     * @param mac
     * @return
     */
    public  Map<String,String> getOpenLockData(Integer adminPwd, String mac){
        return returnMap(jsXxetaUtil.getOpenLockData(adminPwd,mac));
    }

    /**
     * 	添加密码
     * @param baseCode
     * @param pwd
     * @param startTime
     * @param endTime
     * @return
     */
    public  Map<String,String> addBluetoothPwd(Integer basecode, Integer pitNum, Integer pwd){
        if(pitNum==null)  {
        	return returnMap(jsXxetaUtil.addPwd(basecode.toString(),pwd.toString(),1));	
        }
    	  	return returnMap(jsXxetaUtil.addPitNumPwd(basecode,pitNum,pwd));
    }
    
    /**
     * 	添加密码
     * @param baseCode
     * @param pwd
     * @param startTime
     * @param endTime
     * @return
     */
    public  Map<String,String> addTempPwd(Integer basecode,Integer pitNum,Integer pwd,String startTime,String endTime){
    	if(pitNum==null)  {
        	return returnMap(jsXxetaUtil.addTempPwd(basecode.toString(),pwd.toString(),startTime,endTime));	
        }
    	  	return returnMap(jsXxetaUtil.addTempPitNumPwd(basecode.toString(),pitNum.toString(),pwd.toString(),startTime,endTime));
    }
    
	@Override
	public Map<String, String> updateBluetoothPwd(Integer basecode , Integer pitNum, Integer pwd) {
		 if(pitNum==null)  {
	        	return returnMap(jsXxetaUtil.addPwd(basecode.toString(),pwd.toString(),1));	
	        }
	    	  	return returnMap(jsXxetaUtil.addPitNumPwd(basecode,pitNum,pwd));
	}



    /**
     * u1添加密码
     * @param baseCode
     * @param pwd
     * @param startTime
     * @param endTime
     * @return
     */
    public  Map<String,String> addPwd(String baseCode,String pwd,Integer validCount){
    	  return returnMap(jsXxetaUtil.addPwd(baseCode,pwd,validCount));
    }
    /**
     * 	设置管理员密码 O,F,C
     * @param mac
     * @param oldPwd
     * @param newPwd
     */
    public  Map<String,String> setlockAdminPwd(String mac,String oldPwd,String newPwd){
    	return returnMap(jsXxetaUtil.setlockAdminPwd(mac,oldPwd,newPwd));
    }
    
    
    /**
     *	 添加模式
     * @param pitNum
     * @return
     */
    public  Map<String,String> addCard(Integer pitNum,String startTime,String endTime){
    	return returnMap(jsXxetaUtil.addCard(pitNum,startTime,endTime));
    }
    
    /**
     *	 添加指纹
     * @param pitNum
     * @return
     */
    public  Map<String,String> addNewFingerprint(Integer pitNum,String startTime,String endTime){
    	return returnMap(jsXxetaUtil.addNewFingerprint(pitNum,startTime,endTime));
    }
    
    
    /**
     * u1添加卡号
     * @param baseCode
     * @param cardNo
     * @param startTime
     * @param endTime
     * @return
     */
    public  Map<String,String> addCardNo(String baseCode,String cardNo,String startTime,String endTime){
        if(!StringUtil.isNumber(cardNo)){
            cardNo = Long.valueOf(cardNo,16).toString();
        }
        StringBuffer buffer = new StringBuffer("AAAA1410");
        buffer.append(jsXxetaUtil.xxeta(baseCode,startTime,cardNo)).append(jsXxetaUtil.xxeta(baseCode,"1",endTime));
        return returnMap(buffer.toString().toUpperCase());
    }

    /**
                  *       非U/N
     * @param pitNum
     * @return
     */
    public  Map<String,String> delPitNumCardNo(Integer pitNum){
    	return returnMap(jsXxetaUtil.deletePitNumCard(pitNum));
    }
    /**
	  *     删除指纹
	* @param pitNum
	* @return
	*/
	public  Map<String,String> delFinger(Integer pitNum){
	return returnMap(jsXxetaUtil.delFinger(pitNum));
	}  
    
    /**
     * u1删除卡号
     * @param baseCode
     * @param cardNo
     * @return
     */
    public  Map<String,String> delCardNo(Integer baseCode,String cardNo){
    	return returnMap(jsXxetaUtil.delCardNo(baseCode, cardNo));
    }
    /**
     * u1删除密码
     * @param baseCode
     * @param pwd
     * @return
     */
    public  Map<String,String> delPwd(Integer baseCode,String pwd){
    	 return returnMap(jsXxetaUtil.delPwd(baseCode, pwd));
    }
    /**
     *	 非u/n删除密码
     * @param pitNum
     * @return
     */
    public  Map<String,String> delPitNumPwd(Integer pitNum){
    	return returnMap(jsXxetaUtil.delPitNumPwd(pitNum));
    }
    /**
     * *删除离线发的卡
     * @param baseCode
     * @param cardNo
     * @param endTime
     * @return
     */
    public  Map<String,String> delOfflineCardNo(String baseCode, String cardNo, String endTime) {
        if(!StringUtil.isNumber(cardNo)){
            cardNo = Long.valueOf(cardNo,16).toString();
        }
        StringBuffer buffer = new StringBuffer("AAAA1C08");
        buffer.append(jsXxetaUtil.xxeta(baseCode,cardNo,endTime)).append(makeChecksum(buffer.toString()));
        return returnMap(buffer.toString().toUpperCase());
    }

    /**
     * * 恢复删除离线发的卡
     * @param baseCode
     * @param cardNo
     * @return
     */
    public  Map<String,String> recoveryOfflineCardNo(String baseCode, String cardNo) {
        if(!StringUtil.isNumber(cardNo)){
            cardNo = Long.valueOf(cardNo,16).toString();
        }
        StringBuffer buffer = new StringBuffer("AAAA1E08");
        buffer.append(jsXxetaUtil.xxeta(baseCode,"0",cardNo)).append(makeChecksum(buffer.toString()));
        return returnMap(buffer.toString().toUpperCase());
    }

    /***
     *  *删除离线发的限时密码
     * @param baseCode
     * @param pwd
     * @return
     */
    public  Map<String,String> delOfflineTimelimitedPwd(String baseCode, String pwd) {
        StringBuffer buffer = new StringBuffer("AAAA2008");
        buffer.append(jsXxetaUtil.xxeta(baseCode,"0",pwd)).append(makeChecksum(buffer.toString()));
        return returnMap(buffer.toString().toUpperCase());
    }

    /**
     * * 删除离线发的管理密码
     * @param baseCode
     * @param pwd
     * @return
     */
    public  Map<String,String> delOfflineManagePwd(String baseCode, String pwd) {
        StringBuffer buffer = new StringBuffer("AAAA2208");
        buffer.append(jsXxetaUtil.xxeta(baseCode,"0",pwd)).append(makeChecksum(buffer.toString()));
        return returnMap(buffer.toString().toUpperCase());
    }

    /**
      ** 删除所有卡号
     * @param baseCode
     * @param time
     * @return
     */
    public  Map<String,String> delAllCardNo(String baseCode, String time) {
        StringBuffer buffer = new StringBuffer("AAAA2408");
        buffer.append(jsXxetaUtil.xxeta(baseCode,"0",time)).append(makeChecksum(buffer.toString()));
        return returnMap(buffer.toString().toUpperCase());
    }

    /**
     * * 删除所有密码
     * @param baseCode
     * @param time
     * @return
     */
    public  Map<String,String> delAllPwd(String baseCode, String time) {
        StringBuffer buffer = new StringBuffer("AAAA2608");
        buffer.append(jsXxetaUtil.xxeta(baseCode,"0",time)).append(makeChecksum(buffer.toString()));
        return returnMap(buffer.toString().toUpperCase());
    }

    /**
      ** 同步时间
     * @param baseCode
     * @param type
     * @return
     */
    public  Map<String,String> syncTime(String baseCode,String type) {
    	if(!StringUtil.strIsNullOrEmpty(type)&&(type.toUpperCase().contains("O")||type.toUpperCase().contains("C")||type.toUpperCase().contains("F")||type.toUpperCase().contains("D"))) {
    		 return returnMap(jsXxetaUtil.syscTimeNew(baseCode).toUpperCase());	
    	}
    	
        return returnMap(jsXxetaUtil.syscTime(baseCode).toUpperCase());
    }
    /**
     * 	同步时间
     * @param baseCode
     * @param type
     * @return
     */
    public  Map<String,String> syncTime(String baseCode) {
    		 return returnMap(jsXxetaUtil.syscTimeNew(baseCode).toUpperCase());	
    }
    /**
     * F C锁 开锁指令 step1
     * @return
     */
    public  Map<String,String> openLockStep1(String baseCode){
        return returnMap(jsXxetaUtil.sendBasecodeAndN(baseCode).toUpperCase());
    }

    /**
     * F C锁 开锁指令 step2
     * @return
     */
    public  Map<String,String> openLockStep2(String baseCode,String randomN,String subType){
    	Integer n = Integer.parseInt(randomN,16);
        return returnMap(jsXxetaUtil.sendAplusB(baseCode,n.toString(),subType).toUpperCase());
    }
    
    /**
     * *查询电量
     * @return
     */
    public  Map<String, String> selectPower() {
        return returnMap(jsXxetaUtil.selectPower());
    }

    /**
     * *查询绑定状态
     * @return
     */
    public  Map<String, String> selectBindLockStatus() {
        return returnMap(jsXxetaUtil.selectBindLockStatus());
    }

    /**
     ** 读NBimei
     * @return
     */
    public  Map<String, String> readNbImei() {
    	 return returnMap(jsXxetaUtil.queryNbImei());
    }

    public  Map<String,String> returnMap(String data){
        return DataUtil.generateMap("cmdData",data);
    }


    /**
     ** 计算数据校验和
     * @param data
     * @return
     */
    public static String makeChecksum(String data) {
        int total = 0;
        int len = data.length();
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        /**
           * * 用256求余最大是255，即16进制的FF
         */
        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        len = hex.length();
        // 如果不够校验位的长度，补0,这里用的是两位校验
        if (len < 2) {
            hex = "0" + hex;
        }
        return hex.toUpperCase();
    }
    /**
     *  *  读取开锁记录条数
     */
	@Override
	public Map<String, String> readLockEventCount() {
		return returnMap(jsXxetaUtil.readLockEventCount());
	}
	/**
     ** 读取开锁记录条数
     */
	@Override
	public Map<String, String> readLockEventAtIndex(Integer index) {
		return returnMap(jsXxetaUtil.readLockEventAtIndex(index));
	}
	/**
     ** 清除开锁记录
     */
	@Override
	public Map<String, String> clearLockEvents() {
		return returnMap(jsXxetaUtil.clearLockEvents());
	}


	/**
     * 	清除开锁记
     */
	public Map<String, String> offonlinePwd(String time,String baseCode,Integer flag) {
		time = time.replace(" ", "").replace("-", "").replace(":", "");
		String endTime = time.substring(2, time.length() - 2);
		return returnMap(CreateOfflinePasswordUtil.Encryption(endTime, baseCode, flag));
	}
	
	/**
     *	 初始化发卡信息
     */
	public Map<String, String> initCard(String busNum,String mac,String cardCluster) {
		mac = mac.substring(mac.length()/2,mac.length());
		Integer intMac =  Integer.parseInt(mac,16);
		String  doorUnit = intMac.toString().substring(intMac.toString().length()-6, intMac.toString().length()-4);
		String 	doorFloor =  intMac.toString().substring(intMac.toString().length()-4, intMac.toString().length()-2);
		String  roomNum =  intMac.toString().substring(intMac.toString().length()-2, intMac.toString().length());
		return returnMap(jsXxetaUtil.initCard(busNum, doorUnit, doorFloor, roomNum, cardCluster));
	}
	/**
     *	获取baseCode
     */
	public Map<String, String> getBaseCode() {
		return returnMap(ByteTools.convertBytesToHex(4));
	}
	
	/**
	 **配网 
	 */
	public  Map<String, String> connectNetwork(String ssid,String password){
		StringBuffer cn = new StringBuffer("AAAA40");
		String hexSsid = ByteTools.toChineseHex(ssid);
		String hexPassword =ByteTools.toChineseHex(password);
		String ssidData = "0D"+StringUtils.leftPad(Integer.toHexString(hexSsid.length()/2), 2, "0")+hexSsid;
		String passwordData ="0A"+StringUtils.leftPad(Integer.toHexString(hexPassword.length()/2), 2, "0")+hexPassword;
		String length =StringUtils.leftPad( Integer.toHexString((ssidData +passwordData).length()/2)+"", 2, "0");
		cn.append(length).append(ssidData).append(passwordData);
		System.out.println("connectNetwork:"+returnMap(cn.toString()+jsXxetaUtil.makeChecksum(cn.toString())));
		return returnMap(cn.toString()+jsXxetaUtil.makeChecksum(cn.toString()));
	}
	/**
	 * 
	 * @param args
	 */
    public static void main(String[] args) {
    	String mac = "0c5169616E79616E73686131310A084142434431323334";
    	System.out.println(mac.substring(2, mac.length()));
    	String hexSsid = ByteTools.toChineseHex("TP-LINK_932D");
    	String hexPassword =ByteTools.toChineseHex("Iwunu2019");
     	System.out.println(hexSsid);
    	System.out.println(hexPassword);
     	System.out.println(mac.substring(mac.length()-4, mac.length()));
	}

}
